package logic

import (
	"context"
	"fmt"
	"models"
	"time"

	"shop_srv/internal/svc"
	"shop_srv/shop_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type CarPushLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCarPushLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CarPushLogic {
	return &CarPushLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CarPushLogic) CarPush(in *shop_srv.CarPushRequest) (*shop_srv.CarPushResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("card_%d:%d", in.UserId, in.GoodsId)
	e, _ := models.RDB.Exists(models.Ctx, key).Result()
	var goods models.Goods
	if err := models.DB.Where("id = ?", in.GoodsId).Find(&goods).Limit(1).Error; err != nil {
		return nil, err
	}
	fmt.Println(e)
	if e != 0 {
		num, _ := models.RDB.HGet(models.Ctx, key, "Number").Int64()
		num += in.Number
		if num <= 0 {
			models.RDB.Del(models.Ctx, key)
		}
		if goods.Stock < num {
			return nil, fmt.Errorf("库存不足")
		}
		models.RDB.HSet(models.Ctx, key, "Number", num)
	} else {
		if goods.Stock < in.Number {
			return nil, fmt.Errorf("库存不足")
		}
		models.RDB.HSet(models.Ctx, key, "GoodsName", goods.Name, "GoodsTitle", goods.Image, "CreatedAt", time.Now().String(), "Number", in.Number)
	}
	return &shop_srv.CarPushResponse{}, nil
}
